package com.hxkj.controller;

import com.github.pagehelper.PageInfo;
import com.hxkj.domain.po.SysUser;
import com.hxkj.domain.po.UserLoginHistory;
import com.hxkj.service.UserLoginHistoryService;
import com.hxkj.token.TokenGenerator;
import com.platform.common.domain.exception.CustomException;
import com.platform.common.domain.result.ParameterDataStruct;
import com.platform.common.domain.result.ResultDataStruct;
import com.platform.common.domain.result.ResultMessageStruct;
import com.platform.common.domain.to.PageTo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;
import java.util.concurrent.Callable;

/**
 * created by kezhijie on 2018/8/24 15:07.
 * email to kezhijie@hxoss.com
 */
@RestController
@RequestMapping("loginHistory")
@Slf4j
public class UserLoginHistoryController {

    @Autowired
    private UserLoginHistoryService userLoginHistoryService;
    @Autowired
    private TokenGenerator tokenGenerator;

    @PostMapping("get")
    public Callable<ResultDataStruct<PageInfo>> get(@RequestBody ParameterDataStruct<UserLoginHistory> parameterDataStruct) {
        return () -> {
            ResultDataStruct<PageInfo> resultDataStruct = new ResultDataStruct<>();

            try {
                resultDataStruct.setData(userLoginHistoryService.findByUserId(parameterDataStruct.getData(), parameterDataStruct.getPageTo()));
                resultDataStruct.setCode(200);
                resultDataStruct.setMessage("成功");
            } catch (Exception e) {
                log.error("获取历史登录信息失败，", e);
                resultDataStruct.setCode(400);
                resultDataStruct.setMessage("失败");
            }

            return resultDataStruct;
        };
    }

    @PostMapping("record")
    public Callable<ResultMessageStruct> record(@RequestBody UserLoginHistory userLoginHistory) {
        return () -> {
            ResultMessageStruct resultMessageStruct = new ResultMessageStruct();
            try {
                return userLoginHistoryService.save(userLoginHistory);
            } catch (Exception e) {
                log.error("记录用户登录失败， 用户：" + userLoginHistory.getUserId(), e);
                resultMessageStruct.setCode(500);
                resultMessageStruct.setMessage("未知异常");
                return resultMessageStruct;
            }
        };
    }

}
